import { deepClone } from '@/utils/index'
import store from '@/store'
var langTail = store.state.settings.langTail
const componentChild = {}
/**
 * 将./slots中的文件挂载到对象componentChild上
 * 文件名为key，对应JSON配置中的__config__.tag
 * 文件内容为value，解析JSON配置中的__slot__
 */
const slotsFiles = require.context('./slots', false, /\.js$/)
const keys = slotsFiles.keys() || []
keys.forEach(key => {
  const tag = key.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = slotsFiles(key).default
  componentChild[tag] = value
})

function vModel(dataObject, defaultValue,type,confClone) {
  // console.log(confClone)
  if(['radio','checkbox'].includes(confClone.type)){
    dataObject.props.disabled = true
  }
  if(['textarea','firstTitle','text'].includes(confClone.type)){
    dataObject.props.value = confClone['title_'+langTail]
  }else{
    dataObject.props.value = defaultValue
  }

  if(['input'].includes(confClone.type)){
    dataObject.props.placeholder = confClone['title_'+langTail]

    console.log(dataObject.props.placeholder)
  }

  if(type=='textarea' || type=='text'){
    dataObject.props.type = 'textarea'
  }else if(type=='date'|| type=='datetime'){
    // dataObject.props.disabled = true
    dataObject.props.type = type
    dataObject.props.format = confClone.format
    dataObject.props['valueFormat'] = confClone['valueFormat']
  }else if(type=='identCards' || type=='upload'){
    dataObject.props.action='https://jsonplaceholder.typicode.com/posts/'
    dataObject.props.disabled=true
  }else if(type=='switch'){
    dataObject.props.title=confClone['title_'+langTail];
    // dataObject.props['title_tc']=confClone['title_tc'];
    // dataObject.props['title_en']=confClone['title_en'];
  }
  dataObject.on.input = val => {
    this.$emit('input', val)
  }
}

function mountSlotFlies(h, confClone, container) {
  const childObjs = componentChild[confClone.tag]
  if (childObjs) {
    Object.keys(childObjs).forEach(key => {
      const childFunc = childObjs[key]
      if (confClone && confClone[key]) {
        container.push(childFunc(h, confClone, key))
      }
    })
  }
}

function emitEvents(confClone) {
  ['on', 'nativeOn'].forEach(attr => {
    const eventKeyList = Object.keys(confClone[attr] || {})
    eventKeyList.forEach(key => {
      const val = confClone[attr][key]
      if (typeof val === 'string') {
        confClone[attr][key] = event => this.$emit(val, event)
      }
    })
  })
}

function buildDataObject(confClone, dataObject) {
  Object.keys(confClone).forEach(key => {
    const val = confClone[key]
    if (key === 'name') {
      vModel.call(this, dataObject, confClone.defaultValue,confClone.type,confClone)
    } else if (dataObject[key]) {
      dataObject[key] = { ...dataObject[key], ...val }
    } else {
      dataObject.attrs[key] = val
    }
  })

  // 清理属性
  clearAttrs(dataObject)
}

function clearAttrs(dataObject) {
  delete dataObject.attrs
}

function makeDataObject() {
  return {
    attrs: {},
    props: {},
    nativeOn: {},
    on: {},
    style: {}
  }
}

export default {
  props: {
    conf: {
      type: Object,
      required: true
    }
  },
  render(h) {
    const dataObject = makeDataObject()
    const confClone = deepClone(this.conf)
    const container = this.$slots.default || []

    // 如果slots文件夹存在与当前tag同名的文件，则执行文件中的代码
    mountSlotFlies.call(this, h, confClone, container)

    // 将字符串类型的事件，发送为消息
    emitEvents.call(this, confClone)

    // 将json表单配置转化为vue render可以识别的 “数据对象（dataObject）”
    buildDataObject.call(this, confClone, dataObject)

    return h(this.conf.tag, dataObject, container)
  }
}
